<?php


namespace app\service\model;


use app\service\Y;
use think\facade\Cache;

class AdminAuthorityModel extends BaseModel
{
    protected $table = 'admin_authority';

    /**
     * @param $url
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAuthByUrl($url)
    {
        return self::where('path', '=', $url)->find();
    }

    /**
     * 刷新菜单
     * @param $addon
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function refreshMenu($addon): bool
    {
        $tree_name = '../addon/' . $addon . '/config/auth.php';
//        halt($tree_name);
        $tree = require $tree_name;
        self::where('addon', "=", $addon)->delete();
        self::getAddonMenuList($tree, $addon);
        return true;
    }

    /**
     * 获取菜单
     * @param $tree
     * @param $addon
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAddonMenuList($tree, $addon)
    {
        if (!$tree)  return [];

        foreach ($tree as $k => $v) {
            $parent_menu_info = [];
            if (isset($v['parent']) && $v['parent']) {
                $parent_menu_info = self::where('addon', '=', $addon)->where('name', "=", $v['parent'])->find();
            }
            $item = [
                'addon'     => $addon,
                'name'      => $v['name'],
                'title'     => $v['title'],
                'pid'       => $parent_menu_info->id ?? 0,
                'path'      => $v['url'],
                'is_nav'    => $v['is_nav'] ?? 1,
                'sort'      => $v['sort'] ?? 0,
                'icon'      => $v['icon'] ?? '',
            ];
            self::insert($item);
        }
        return true;
    }

    /**
     * 菜单树转化为列表
     * @param $tree
     * @param $app_module
     * @param string $addon
     * @param string $parent
     * @param int $level
     */
    private function menuTreeToList($tree, $app_module, $addon = '', $parent = '', $level = 1)
    {
        if (is_array($tree)) {
            foreach ($tree as $key => $value) {
                $item = [
                    'app_module' => $app_module,
                    'addon' => $addon,
                    'title' => $value['title'],
                    'name' => $value['name'],
                    'parent' => $parent,
                    'level' => $level,
                    'url' => $value['url'],
                    'is_show' => $value['is_show'] ?? 1,
                    'sort' => $value['sort'] ?? 100,
                    'is_icon' => $value['is_icon'] ?? 0,
                    'picture' => $value['picture'] ?? '',
                    'picture_select' => $value['picture_select'] ?? '',
                    'is_control' => $value['is_control'] ?? 1,
                    'desc' => $value['desc'] ?? '',
                ];
                $refer = $value;
                if (isset($refer['child_list'])) {
                    unset($refer['child_list']);
                    array_push($this->list, $item);
                    $p_name = $refer['name'];
                    $this->menuTreeToList($value['child_list'], $app_module, $addon, $p_name, $level + 1);
                } else {
                    array_push($this->list, $item);
                }
            }
        }
    }

    /**
     * 保存数据
     * @param $param
     * @param $id
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveAuth($param, $id) {
        if ($id > 0) {
            $query = self::where('id', '<>', $id)->where(function ($query) use ($param) {
                $query->where('title', '=', $param['title']);
                if ($param['name']) {
                    $query->whereOr('name', '=', $param['name']);
                }
                if ($param['path'])
                    $query->whereOr('path', '=', $param['path']);
            });

            if ($query->find()) {
                return Y::error('名称或者路劲已存在');
            }

            $auth = self::find($id);
            if (!$auth) {
                return Y::error('参数错误');
            }

            $auth->save($param);
        } else {
            $query = self::where('title', '=', $param['title']);

            if ($param['name']) {
                $query->whereOr('name', '=', $param['name']);
            }

            if ($param['path'])
                $query->whereOr('path', '=', $param['path']);

            if ($query->find()) {
                return Y::error('名称或者路劲已存在');
            }
            self::create($param);
        }
        Cache::tag('admin_cache')->clear();
        return Y::success([], '保存成功');
    }
}